package com.calvin.study.multithread.threadpool;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import com.calvin.study.utils.Print;
import static com.calvin.study.utils.ThreadUtil.sleepMilliSeconds;
import static com.calvin.study.utils.ThreadUtil.sleepSeconds;

public class ThreadPoolDemo05 {
    public static final int SLEEP_GAP = 500;

	 //异步的执行目标类
    public static class TargetTask implements Runnable {
        static AtomicInteger taskNo = new AtomicInteger(1);
        protected String taskName;

        public TargetTask() {
            taskName = "task-" + taskNo.get();
            taskNo.incrementAndGet();
        }

        public void run() {

            Print.tco("任务：" + taskName + " doing");
            // 线程睡眠一会
            sleepMilliSeconds(SLEEP_GAP);

            Print.tco(taskName + " 运行结束.");
        }

        @Override
        public String toString() {
            return "TargetTask{" + taskName + '}';
        }
    }
	
    //线程工厂类，创建线程用。
	static public class SimpleThreadFactory implements ThreadFactory {
		static AtomicInteger threadNo = new AtomicInteger(1);

		@Override
		public Thread newThread(Runnable target) {
			String threadName = "simpleThread-" + threadNo.get();
			Print.tco("创建一条线程，名称为：" + threadName);
			threadNo.incrementAndGet();
			// 设置线程名称
			Thread thread = new Thread(target, threadName);
			// 设置为守护线程
			thread.setDaemon(true);
			return thread;
		}
	}
	
	public static class CustomIgnorePolicy implements RejectedExecutionHandler{

		@Override
		public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
			// 可做日志记录等
			Print.tco(r + " rejected; " + " - getTaskCount: " + e.getTaskCount());
		}
		
	}
	
	//测试自定义异常策略
    public static void testCustomIgnorePolicy() {
    	TimeUnit unit = TimeUnit.SECONDS;
    	
        int corePoolSize = 2; //核心线程数
        int maximumPoolSize = 4;  //最大线程数
        long keepAliveTime = 10;
        //最大排队任务数
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(2);
        
        //拒绝和异常策略
        RejectedExecutionHandler policy = new CustomIgnorePolicy();
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime, unit,
                workQueue,
                new SimpleThreadFactory(),
                policy);

        // 预启动所有核心线程
        pool.prestartAllCoreThreads();
        
        for (int i = 1; i <= 10; i++) {
            pool.execute(new TargetTask());
        }
        
        //等待10秒
        sleepSeconds(10);
        Print.tco("关闭线程池");
        pool.shutdown();
    }
    
    public static void main(String[] args) {
		testCustomIgnorePolicy();
	}

}
